package cn.wolfcode.wolf2w.advice;

import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 通用异常处理类
 * 请求进入controller映射方法之前做功能增强：日期格式化（dateFormat）等
 * 请求进入controller映射方法之后做功能增强：统一异常处理等
 */
@ControllerAdvice   // 功能增强注解，动态代理controller类实现的一些额外的功能
public class CommonsExceptionHandler {

    @ExceptionHandler(LogicException.class)  // 捕获用户异常
    @ResponseBody
    public Object LogicExceptionHandler(Exception e, HttpServletResponse response){
        e.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        // 方法2：不用@ResponseBody 返回json
        // response.getWriter().write(JSON.toJSONString(JsonResult.error(JsonResult.CODE_ERROR_PARAM,e.getMessage(),null)));
        return JsonResult.error(JsonResult.CODE_ERROR_PARAM,e.getMessage(),null);
    }

    @ExceptionHandler(RuntimeException.class)  // 捕获系统异常
    @ResponseBody
    public Object RuntimeExceptionHandler(Exception e, HttpServletResponse response){
        e.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        // 方法2：不用@ResponseBody 返回json
        // response.getWriter().write(JSON.toJSONString(JsonResult.defaultError()));
        return JsonResult.defaultError();
    }
}
